/*
 * @Author: chenr 526963089@qq.com
 * @Date: 2023-02-15 16:05:31
 * @LastEditors: chenr 526963089@qq.com
 * @LastEditTime: 2023-03-01 17:24:26
 * @FilePath: /library-web/src/src-portal/stores/async-routers.ts
 * @Description: 异步路由
 */
import { defineStore } from 'pinia';
import { getMenus } from '@/api/mock';
import { notFoundRouter } from '@/router';
import { rootRouter, constantRouterComponents } from '../router';
import { createMenusRouter } from '@/router/generatorRouter';
import { cloneDeep } from 'lodash-es';
import { SRC_PORTAL } from '@/constants/config';
import type { RouterInterface } from '@/router/types';

/* 类型 */
type StateType = {
  routers: RouterInterface | undefined; // 拼装后的routers - 最终被router.addRoute
  addRouters: RouterInterface[] | undefined; // 动态添加项
};
export const useRouterStore = defineStore({
  id: `${SRC_PORTAL}_router`,
  state: (): StateType => ({
    routers: undefined,
    addRouters: undefined,
  }),
  actions: {
    /**
     * @description: 删除路由状态
     * @return {*}
     */
    removeState() {
      delete this.$state.routers;
      delete this.$state.addRouters;
    },

    /**
     * @description: 异步获取菜单
     * @return {*}
     */
    async generatorDynamicRouter() {
      const res = await getMenus();
      const addRouters = createMenusRouter(res, constantRouterComponents, SRC_PORTAL);
      const cloneRootRouter = cloneDeep(rootRouter);
      cloneRootRouter.children = [...addRouters, notFoundRouter];
      this.addRouters = [...addRouters];
      this.routers = cloneRootRouter;
      return this.routers;
    },
  },
});
